package com.okilo.online.app.base

import android.app.AlertDialog
import android.content.Context
import android.os.Bundle
import android.view.View
import com.okilo.online.app.R
import com.okilo.online.app.common.OkiloComAct
import com.okilo.online.app.tools.apt.OkiloOnSingleClickListener
import com.okilo.online.app.tools.extensions.getStringRes
import com.okilo.online.app.tools.manager.OkiloLoadingManager
import com.okilo.online.app.tools.manager.OkiloToastManager

abstract class OkiloBaseDlog(
    context: Context,
    style: Int = R.style.DialogTheme
) : AlertDialog(context, style), IOkiloBaseView, View.OnClickListener {

    private var loadingManager: OkiloLoadingManager? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(createOkiloContentView())
        initializeOkiloWindow()
        initializeOkiloViews()
        setupOkiloEventListeners()
        loadOkiloData()
    }

    protected abstract fun createOkiloContentView(): View

    /**
     * 初始化Window
     */
    protected abstract fun initializeOkiloWindow()

    /**
     * 初始化布局
     */
    protected abstract fun initializeOkiloViews()

    /**
     * 初始化监听
     */
    protected abstract fun setupOkiloEventListeners()

    /**
     * 初始化数据
     */
    protected abstract fun loadOkiloData()

    /**
     * 控件点击事件
     */
    protected abstract fun onOkiloEventViewClick(v: View?)

    // 获取页面名称，子类必须实现
    protected abstract val dialogName: String
    //备注信息
    protected open var dialogRemark: String = ""
    // 是否启用页面埋点（默认启用）
    protected open val enableDialogTrack: Boolean = true

    override fun showOkiloLoading() {
        showOkiloLoading(context.getStringRes(R.string.okilo_loading))
    }

    fun showOkiloLoading(msg: String = "") {
        if (loadingManager == null){
            loadingManager = OkiloLoadingManager(context as OkiloComAct)
        }
        loadingManager?.showLoading(msg)
    }

    override fun hideOkiloLoading() {
        loadingManager?.dismissLoading()
    }

    override fun showOkiloToast(s: String?) {
        OkiloToastManager.showShortText(context, s)
    }

    override fun onClick(v: View) {
        onOkiloEventViewClick(v)
    }

    protected fun setOnClickListener(view: View) {
        view.setOnClickListener(object : OkiloOnSingleClickListener() {
            override fun onSingleClick(v: View) {
                onOkiloEventViewClick(v)
            }
        })
    }

    protected fun setOnClickListener(vararg views: View) {
        views.forEach { view ->
            view.setOnClickListener(object : OkiloOnSingleClickListener() {
                override fun onSingleClick(v: View) {
                    onOkiloEventViewClick(v)
                }
            })
        }
    }

    override fun dismiss() {
        super.dismiss()
        loadingManager?.dismissLoading()
    }
}
